/******************************************************************************
* Copyright (C) 2017 ShenZhen 
* All Rights Reserved.
*****************************************************************************/

package com.lobby.httpclient;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.lobby.httpclient.EncryptUtils.Encrypt;
/**
* @Title:
* @author  TODO
* @since   JDK1.6
* @history 2017年11月9日 TODO 新建
*/
public class SignUtils {
    
    public static final String SECRET_KEY = "secret"; 
    public static final String SECRET = "C28A4BAEA41EF58F08C1";

    public static String getSignature(Map<String, String> params) {
        return getSignature(params, Encrypt.MD5);
    }
    
    public static String getSignature(Map<String, String> params, Encrypt encryptMethod) {
        if (null == params || params.isEmpty()) {
            return null;
        }
        //1.对参数key按字典顺序进行排序
        String[] keys = setToArray(params.keySet());
        Arrays.sort(keys);
        //2.拼装参数字符
        String[] excludeKeyArr = {"signature", "sign", "ts", "sign_type"};
        List<String> excludeKey = Arrays.asList(excludeKeyArr);
        StringBuilder paramSb = new StringBuilder(100);
        for (String key : keys) {
            if (excludeKey.contains(key)) {
                continue;
            }
            if (!params.containsKey(key)) {
                continue;
            }
            String value = params.get(key);
            try {
                value = URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (null == value || "".equals(value)) {
                continue;
            }
            paramSb.append(key).append('=').append(value).append('&');
        }
        
        //3. 添加secret
        paramSb.append(SECRET_KEY).append('=').append(SECRET);
        //System.out.println(paramSb.toString());
        
        //4.加密签名
        String signature = EncryptUtils.encryptString(paramSb.toString(), Encrypt.MD5);
        
        return signature;
    }
    
    public static void main(String[] args) {
        String url = "https://openapi.colourlife.com/v1/gfjg/pay/unifiedorder";
        Map<String, String> testParam = new HashMap<String, String>();
        testParam.put("business_uuid","e3ccf625-ee0e-44a4-b138-fa02859dea04");
        testParam.put("device_info", "CZYAPP");
        testParam.put("open_id", "e80fe9a4390523ff25cd9ee57ce7cd49");
        testParam.put("mobile", "13424367370");
        testParam.put("nonce_str", "llusc9e5l3ttpv2na0krvtpbdtqaq7ikmatnpvfl");
        testParam.put("body", "e安全-人脸识别费用");
        testParam.put("detail", "123");
        testParam.put("out_trade_no", "20171106145058");
        testParam.put("total_fee", "30");
        testParam.put("meal_total_fee", "30");
        testParam.put("spbill_create_ip", "120.26.112.214");
        testParam.put("notify_url", "https://wwl.ycws.cc/h5/csh/pay.jsp");
        testParam.put("trade_type", "JSAPI");
        testParam.put("scene_info", "1000");
        testParam.put("sign", "a4ee39db65e231f08136c777ab7ac2ba");
        testParam.put("ts","1520990325");
        testParam.put("appID", "ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED");
        testParam.put("signature", getSignature(testParam));
        String md5=getSignature(testParam);
        System.out.println("===md5==="+md5);
        String param = buildParams(testParam);
        System.out.println(param);
        String responseStr = HttpUtils.sendPost(url, param);
        System.out.println(responseStr);
    }
    
    public static String buildParams(Map<String, String> params) {
        if (null == params || params.isEmpty()) {
            return null;
        }
        
        StringBuilder sb = new StringBuilder(200);
        for (String key : params.keySet()) {
            sb.append(key).append('=').append(params.get(key)).append('&');
        }
        
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        
        return sb.toString();
    }
    
    public static String[] setToArray(Set<String> sets){
        if (null == sets || sets.isEmpty()) {
            return new String[0];
        }
        
        String[] result = new String[sets.size()];
        int index = 0;
        for (String str : sets) {
            result[index++] = str;
        }
        return result;
    }
}
